package com.weiz.controller.excel;

import com.alibaba.excel.EasyExcel;
import com.alibaba.excel.context.AnalysisContext;
import com.alibaba.excel.event.AnalysisEventListener;
import com.weiz.domain.excel.Person;
import org.springframework.core.io.ClassPathResource;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.InputStream;
import java.net.URLEncoder;
import java.nio.file.Files;
import java.nio.file.Path;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

@RestController
public class ExcelOpController {


    @GetMapping("/downloadTemplate")
    public ResponseEntity<byte[]> downloadTemplate() throws IOException {
        // 定义模板文件路径
        String templatePath = "model/模板01.xlsx";

        // 加载模板文件为资源
        ClassPathResource resource = new ClassPathResource(templatePath);

        InputStream inputStream = resource.getInputStream();
        byte[] data = InputStreamToByteArray.inputStreamToByteArray(inputStream);
        // 对 byteArray 进行操作，比如打印长度
        System.out.println("字节数组长度: " + data.length);

//        Path path = resource.getFile().toPath();
//        byte[] data = Files.readAllBytes(path);

        // 设置响应头
        HttpHeaders headers = new HttpHeaders();
        headers.setContentType(MediaType.APPLICATION_OCTET_STREAM);
        headers.setContentDispositionFormData("attachment", URLEncoder.encode("模板01.xlsx", "UTF-8"));

        return new ResponseEntity<>(data, headers, HttpStatus.OK);
    }


//    http://localhost:8080//uploadExcelWithEasyExcel
    @PostMapping("/uploadExcelWithEasyExcel")
    public List<Person> uploadExcelWithEasyExcel(@RequestParam("file") MultipartFile file) {
        List<Person> personList = new ArrayList<>();
        if (file.isEmpty()) {
            return personList;
        }
        try {
            EasyExcel.read(file.getInputStream(), Person.class, new AnalysisEventListener<Person>() {
                @Override
                public void invoke(Person person, AnalysisContext analysisContext) {
                    personList.add(person);
                }

                @Override
                public void doAfterAllAnalysed(AnalysisContext analysisContext) {
                    // 所有数据解析完成后的操作，这里可以按需添加逻辑
                }
            }).sheet().doRead();
        } catch (IOException e) {
            e.printStackTrace();
        }
        for (Person person : personList) {
            System.out.println(person);
        }
        return personList;
    }

    /*
    * body json
    *
    {
        "name":"张三"
        ,"age":25
        ,"jobDate":"2021-01-12"
    }
    * */
    @GetMapping("/exportListPerson")
    public void exportListPerson(HttpServletResponse response,@RequestBody Person param) throws IOException {
        // 设置响应头
        response.setContentType("application/vnd.ms-excel");
        response.setCharacterEncoding("utf-8");

        // 设置文件名
        String fileName = "用户信息.xlsx";
        response.setHeader("Content-disposition", "attachment;filename=" + URLEncoder.encode(fileName, "UTF-8"));

        // 数据列表
        List<Person> listPerson = prepareData();

        // 使用 EasyExcel 写入到响应输出流
        EasyExcel.write(response.getOutputStream(), Person.class).sheet("用户信息").doWrite(listPerson);
    }

    private List<Person> prepareData() {
        SimpleDateFormat sdf =new SimpleDateFormat("yyyy-MM-dd");
        try {
            return Arrays.asList(
                    new Person("张三", 25, sdf.parse("2020-01-01")),
                    new Person("李四", 30, sdf.parse("2020-01-12")),
                    new Person("王五", 22, sdf.parse("2020-01-03"))
            );
        } catch (ParseException e) {
            throw new RuntimeException(e);
        }
    }

}